/****************************************************************************
**
** This file is part of qPhotoTag, a photo keywording application
**
** Copyright (C) 2009 Marcell Lengyel <miketkf@gmail.com>
**
** GNU General Public License
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**
****************************************************************************/

#include <QtGui>
#include "mainwindowimpl.h"
#include "wptlistdialog.h"
#include "gpxwpt.h"
#include "centraleurroman.h"
//
MainWindowImpl::MainWindowImpl() 
{
	this->resize(800,600);
	createActions();
        createMenus();
	createToolBars();
	createStatusBar();
	createLayout();
	setUnifiedTitleAndToolBarOnMac(true);
        read_settings();
        setWindowTitle(tr("qPhotoTag"));
        QCoreApplication::setOrganizationName("Marcell Lengyel");
        QCoreApplication::setOrganizationDomain("miketkf.com");
        QCoreApplication::setApplicationName("qPhotoTag");
	(void)new QCentralEurRomanCodec();
}

MainWindowImpl::~MainWindowImpl()
{
    save_settings();
}

void MainWindowImpl::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(openAct);
    fileMenu->addAction(saveAct);
    fileMenu->addAction(geotagAct);
    fileMenu->addSeparator();
    fileMenu->addAction(preferencesAct);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAct);

    helpMenu = menuBar()->addMenu(tr("&Help"));
    helpMenu->addAction(aboutAct);
}

void MainWindowImpl::read_settings()
{
    QSettings settings;
    QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
    QSize size = settings.value("size", QSize(800, 600)).toSize();
    resize(size);
    move(pos);
    shortcuts.clear();
    int settings_size = settings.beginReadArray("shortcuts");
    for (int i = 0; i < settings_size; ++i) {
        settings.setArrayIndex(i);
        SHORTCUT shortcut;
        shortcut.key = settings.value("key").toInt();
        shortcut.modifiers = settings.value("modifiers").toUInt();
        shortcut.shortcut_text = settings.value("shortcut_text").toString();
        shortcut.keywords = settings.value("keywords").toString();
        shortcuts.append(shortcut);
    }
    settings.endArray();
}

void MainWindowImpl::save_settings()
{
    /* Save postion/size of main window */
    QSettings settings;
    settings.setValue("pos", pos());
    settings.setValue("size", size());
}

void MainWindowImpl::geotag()
{
    // first, read the settings and see if there is a saved .gpx file
    QSettings settings;
    QString wpt_file_name = settings.value("waypointFile", QString("")).toString();
    if (wpt_file_name.isEmpty() || ! QFileInfo(wpt_file_name).isReadable()) {
        wpt_file_name = select_waypoint_file();
        if (! wpt_file_name.isEmpty())
            settings.setValue("waypointFile", wpt_file_name);
    }
    if (! wpt_file_name.isEmpty() && QFileInfo(wpt_file_name).isReadable())
    {
        QFile wpt_file(wpt_file_name);
        WptListDialog wpt_dialog(wpt_file, this);
        wpt_dialog.exec();
        GpxWpt wpt_data = wpt_dialog.selectedWaypoint();
        qDebug("Selected waypoint: %s\n", wpt_data.name.toAscii().data());
        if ((wpt_data.lat != 0) && (wpt_data.lon != 0)) {
            photoview->update_gps_coordinates_to_selected(wpt_data.lat,
                                                          wpt_data.lon,
                                                          wpt_data.altitude);
            // refresh
            on_photoview_selection_changed(QItemSelection(), QItemSelection());
            saveAct->setEnabled(true);
        }
    }

}

void MainWindowImpl::createActions()
{
	openAct = new QAction(QIcon(":/icons/open.svg"), tr("&Open..."), this);
	openAct->setShortcuts(QKeySequence::Open);
	openAct->setStatusTip(tr("Open photos"));
	connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

	saveAct = new QAction(QIcon(":/icons/save.svg"), tr("&Save..."), this);
	saveAct->setShortcuts(QKeySequence::Save);
	saveAct->setStatusTip(tr("Save the modified EXIF/IPTC info"));
	connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));

        geotagAct = new QAction(QIcon(":/icons/globe.svg"), tr("&Geotag"), this);
	geotagAct->setShortcut(tr("Ctrl+G"));
	geotagAct->setStatusTip(tr("Geotag the selected pictures"));
	connect(geotagAct, SIGNAL(triggered()), this, SLOT(geotag()));
	
	exitAct = new QAction(QIcon(":/icons/quit.svg"), tr("E&xit"), this);
	exitAct->setShortcut(tr("Ctrl+Q"));
	exitAct->setStatusTip(tr("Exit the application"));
	connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));

        aboutAct = new QAction(tr("&About"), this);
        aboutAct->setStatusTip(tr("About qPhotoTag"));
        connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));

        preferencesAct =  new QAction(QIcon(":/icons/preferences.svg"), tr("Prefere&nces"), this);
        preferencesAct->setStatusTip(tr("Edit qPhotoTag preferences"));
        connect(preferencesAct, SIGNAL(triggered()), this, SLOT(preferences()));

        saveAct->setEnabled(false);
        geotagAct->setEnabled(false);
}

void MainWindowImpl::createToolBars()
{
	toolBar = addToolBar(tr("File"));
	toolBar->addAction(openAct);
	toolBar->addAction(saveAct);
	toolBar->addAction(geotagAct);
	toolBar->addAction(exitAct);
}

void MainWindowImpl::createStatusBar()
{
    progressBar = new QProgressBar;
    statusBar()->addPermanentWidget(progressBar);
    progressBar->hide();
    statusBar()->showMessage(tr("Ready"));
}

void MainWindowImpl::createLayout()
{
        this->setStyleSheet("QGroupBox::indicator:unchecked { image: url(:/icons/gray_right.png);}"
                            "QGroupBox::indicator:checked { image: url(:/icons/gray_down.png);}");

        captionGroup = new QGroupBox(tr("Caption"), this);
        caption_entry = new CaptionEdit(this);
        caption_entry->setToolTip("The text entered here will be set as <i>Iptc.Application2.Caption</i>");
        captionGroupLayout = new QVBoxLayout(captionGroup);
        captionGroupLayout->addWidget(caption_entry);
	captionGroup->setMaximumHeight(100);
        captionGroup->setFlat(true);
        captionGroup->setCheckable(true);
        captionGroup->setChecked(true);
	
        tagListGroup = new QGroupBox(tr("Tags for selected photos"), this);
        tag_list = new TagList(this);
        tag_list->setToolTip("This list shows the tags that are common for the selected photos");
	QVBoxLayout *tagListGroupLayout = new QVBoxLayout(tagListGroup);
	tagListGroupLayout->addWidget(tag_list);
        tagListGroup->setFlat(true);
        tagListGroup->setCheckable(true);
        tagListGroup->setChecked(true);

	
        add_tag_entry = new QLineEdit(this);
	// IPTC keyword max length is 64
	add_tag_entry->setMaxLength(64);
        add_tag_entry->setToolTip("The text entered here will be added to the selected photos as "
                                  "<i>Iptc.Application2.Keywords</i>");
        add_tag_button = new QPushButton(tr("Add tag"), this);
        QWidget *add_tag_frame = new QWidget(this);
	QHBoxLayout *add_tag_layout = new QHBoxLayout(add_tag_frame);
	add_tag_layout->addWidget(add_tag_entry);
	add_tag_layout->addWidget(add_tag_button);

        tagPoolGroup = new QGroupBox(tr("Tag pool"), this);
        tag_pool = new TagList(this);
        tag_pool->setToolTip("The list of all available keywords.<br>"
                             "By doble clicking on any of them adds it to the selected photos.");
	QVBoxLayout *tagPoolGroupLayout = new QVBoxLayout(tagPoolGroup);
	tagPoolGroupLayout->addWidget(tag_pool);
        tagPoolGroup->setFlat(true);
        tagPoolGroup->setCheckable(true);
        tagPoolGroup->setChecked(true);

        add_button = new QPushButton(tr("Add selected"), this);
        remove_button = new QPushButton(tr("Remove selected"), this);
        QWidget *add_remove_frame = new QWidget(this);
	QHBoxLayout *add_remove_layout = new QHBoxLayout(add_remove_frame);
	add_remove_layout->addWidget(add_button);
	add_remove_layout->addWidget(remove_button);

        lens_data_group = new QGroupBox(tr("Lens data"), this);
        QGridLayout *lens_data_grid = new QGridLayout(lens_data_group);
        lens_cbox = new QCheckBox(tr("Lens model:"), this);
        lens_cbox->setTristate(true);
        lens_data_grid->addWidget(lens_cbox, 0, 0, 1, 1);
        lens_combo = new QComboBox(this);
        lens_combo->setEditable(true);
        lens_combo->setInsertPolicy(QComboBox::InsertAtTop);
        lens_combo->setToolTip("If the camera maker is <i>Canon</i> then the value of this field "
                               "is added to the <i>Exif.Canon.0x0095</i> EXIF tag.");
        lens_data_grid->addWidget(lens_combo, 0,1,1,2);
        //
        max_aperture_cbox = new QCheckBox(tr("Max aperture:"), this);
        max_aperture_cbox->setTristate(true);
        lens_data_grid->addWidget(max_aperture_cbox, 1,0,1,1);
        max_aperture_sbox = new QDoubleSpinBox(this);
        max_aperture_sbox->setToolTip("The value entered here will be set in "
                                      "<i>Exif.Photo.MaxApertureValue</i> and if the camera maker is "
                                      "<i>Canon</i> then in <i>Exif.CanonCs.MaxAperture</i> too.");
        max_aperture_sbox->setMinimum(0);
        max_aperture_sbox->setMaximum(64);
        max_aperture_sbox->setDecimals(1);
        max_aperture_sbox->setSpecialValueText(tr("N/A"));
        lens_data_grid->addWidget(max_aperture_sbox, 1,2,1,1);
        //
        fnumber_cbox = new QCheckBox(tr("F number:"), this);
        fnumber_cbox->setTristate(true);
        lens_data_grid->addWidget(fnumber_cbox, 2,0,1,1);
        fnumber_sbox = new QDoubleSpinBox(this);
        fnumber_sbox->setToolTip("The value entered here will be set in the following EXIF tags:<br>"
                                 "- <i>Exif.Photo.FNumber</i><br>- <i>Exif.Photo.ApertureValue</i>");
        fnumber_sbox->setMinimum(0);
        fnumber_sbox->setMaximum(64);
        fnumber_sbox->setDecimals(1);
        fnumber_sbox->setSpecialValueText(tr("N/A"));
        lens_data_grid->addWidget(fnumber_sbox, 2,2,1,1);
        //
        focal_cbox = new QCheckBox(tr("Focal length:"), this);
        focal_cbox->setTristate(true);
        lens_data_grid->addWidget(focal_cbox, 3,0,1,1);
        focal_sbox = new QDoubleSpinBox(this);
        focal_sbox->setToolTip("The value entered here will be set in the <i>Exif.Photo.FocalLength</i> "
                               "EXIF tag.");
        focal_sbox->setMinimum(0);
        focal_sbox->setMaximum(1200);
        focal_sbox->setSuffix(tr(" mm"));
        focal_sbox->setDecimals(1);
        focal_sbox->setSpecialValueText(tr("N/A"));
        lens_data_grid->addWidget(focal_sbox, 3,2,1,1);
        //
        lens_data_group->setFlat(true);
        lens_data_group->setCheckable(true);
        lens_data_group->setChecked(false);
        lens_combo->setVisible(false);
        max_aperture_sbox->setVisible(false);
        fnumber_sbox->setVisible(false);
        focal_sbox->setVisible(false);
        lens_cbox->setVisible(false);
        max_aperture_cbox->setVisible(false);
        fnumber_cbox->setVisible(false);
        focal_cbox->setVisible(false);
        //
        QWidget *frameEntries = new QWidget(this);
	frameEntries->setMaximumWidth(300);
	QVBoxLayout *entryLayout = new QVBoxLayout(frameEntries);
	entryLayout->addWidget(captionGroup);
	entryLayout->addWidget(tagListGroup);
	entryLayout->addWidget(add_tag_frame);
	entryLayout->addWidget(tagPoolGroup);
	entryLayout->addWidget(add_remove_frame);
        entryLayout->addWidget(lens_data_group);
	
        photoview = new PhotoView(this);
	connect(photoview->selectionModel(), 
			SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
			this, 
			SLOT(on_photoview_selection_changed(const QItemSelection &, const QItemSelection &)));
        connect(photoview,
                        SIGNAL(doubleClicked(const QModelIndex &)),
                        this,
                        SLOT(on_photoview_doubleclick(const QModelIndex &)));
        connect(add_tag_button,
			SIGNAL(clicked()),
			this,
			SLOT(on_add_tag_clicked()));
	connect(add_tag_entry,
			SIGNAL(returnPressed()),
			this,
			SLOT(on_add_tag_clicked()));
	connect(add_button,
			SIGNAL(clicked()),
			this,
			SLOT(on_add_button_clicked()));
        connect(tag_pool,
                        SIGNAL(doubleClicked(const QModelIndex &)),
                        this,
                        SLOT(on_add_button_clicked()));
        connect(remove_button,
                        SIGNAL(clicked()),
                        this,
                        SLOT(on_remove_button_clicked()));
        connect(tag_list,
                        SIGNAL(tagListFocusIn()),
                        this,
                        SLOT(on_tag_list_focus_in()));
        connect(tag_pool,
                        SIGNAL(tagListFocusIn()),
                        this,
                        SLOT(on_tag_pool_focus_in()));
        connect(caption_entry,
                        SIGNAL(captionEditChanged()),
                        this,
                        SLOT(on_caption_changed()));
        connect(captionGroup,
                        SIGNAL(toggled(bool)),
                        caption_entry,
                        SLOT(setVisible(bool)));
        connect(tagListGroup,
                        SIGNAL(toggled(bool)),
                        tag_list,
                        SLOT(setVisible(bool)));
        connect(tagPoolGroup,
                        SIGNAL(toggled(bool)),
                        tag_pool,
                        SLOT(setVisible(bool)));
        connect(lens_data_group,
                        SIGNAL(toggled(bool)),
                        this,
                        SLOT(toggle_lens_data_group(bool)));
        connect(lens_cbox,
                        SIGNAL(stateChanged(int)),
                        this,
                        SLOT(set_lens_data()));
        connect(max_aperture_cbox,
                        SIGNAL(stateChanged(int)),
                        this,
                        SLOT(set_lens_data()));
        connect(fnumber_cbox,
                        SIGNAL(stateChanged(int)),
                        this,
                        SLOT(set_lens_data()));
        connect(focal_cbox,
                        SIGNAL(stateChanged(int)),
                        this,
                        SLOT(set_lens_data()));
        connect(max_aperture_sbox,
                        SIGNAL(editingFinished()),
                        this,
                        SLOT(set_lens_data()));
        connect(fnumber_sbox,
                        SIGNAL(editingFinished()),
                        this,
                        SLOT(set_lens_data()));
        connect(focal_sbox,
                        SIGNAL(editingFinished()),
                        this,
                        SLOT(set_lens_data()));
        connect(lens_combo,
                        SIGNAL(editTextChanged(QString)),
                        this,
                        SLOT(set_lens_data()));
        connect(lens_combo,
                        SIGNAL(currentIndexChanged(int)),
                        this,
                        SLOT(set_lens_data()));

        caption_entry->setEnabled(false);
        add_tag_button->setEnabled(false);
        add_tag_entry->setEnabled(false);
        add_button->setEnabled(false);
        remove_button->setEnabled(false);
        tag_list->setEnabled(false);
        tag_pool->setEnabled(false);
        lens_combo->setEnabled(false);
        max_aperture_sbox->setEnabled(false);
        fnumber_sbox->setEnabled(false);
        focal_sbox->setEnabled(false);
        lens_cbox->setEnabled(false);
        max_aperture_cbox->setEnabled(false);
        fnumber_cbox->setEnabled(false);
        focal_cbox->setEnabled(false);

        QWidget *centralWidget = new QWidget(this);
	QHBoxLayout *hbox = new QHBoxLayout(centralWidget);
	hbox->addWidget(frameEntries);
	hbox->addWidget(photoview);
	
	setCentralWidget(centralWidget);
}

void MainWindowImpl::set_lens_data()
{
    photoview->set_lens_data_for_selected(lens_combo->currentText(),
                                          lens_cbox->checkState(),
                                          max_aperture_sbox->value(),
                                          max_aperture_cbox->checkState(),
                                          fnumber_sbox->value(),
                                          fnumber_cbox->checkState(),
                                          focal_sbox->value(),
                                          focal_cbox->checkState());
    // if any checkbox is active, enable the save action
    if (lens_cbox->checkState() == Qt::Checked ||
                max_aperture_cbox->checkState() == Qt::Checked ||
                fnumber_cbox->checkState() == Qt::Checked ||
                focal_cbox->checkState() == Qt::Checked)
        saveAct->setEnabled(true);
}

void MainWindowImpl::toggle_lens_data_group(bool visible)
{
    QObject *o;
    foreach(o, lens_data_group->children()) {
        if (o->isWidgetType())
            qobject_cast<QWidget*>(o)->setVisible(visible);
    }
}

void MainWindowImpl::on_caption_changed()
{
    if (photoview->is_selection())
    {
        photoview->add_caption_to_selected(caption_entry->toPlainText());
        saveAct->setEnabled(true);
    }
}


void MainWindowImpl::on_remove_button_clicked()
{
	if (photoview->is_selection() && tag_list->is_selection())
	{
		QStringList tags_to_remove = QStringList(tag_list->get_selected_tags());
		photoview->remove_tags_from_selected(tags_to_remove);
		// refresh the view
		on_photoview_selection_changed(QItemSelection(),QItemSelection());
                saveAct->setEnabled(true);
	}
}

void MainWindowImpl::on_add_button_clicked()
{
	if (photoview->is_selection() && tag_pool->is_selection())
	{
		photoview->add_tags_to_selected(tag_pool->get_selected_tags());
		// merge the existing tag_list and the selected tags from the tag_pool
		QStringListModel *tlm = (QStringListModel *)tag_list->model();
		QStringList merged_list = QStringList(tlm->stringList());
		QStringList selected_tags = QStringList(tag_pool->get_selected_tags());
		for ( QStringList::iterator it = selected_tags.begin(); it != selected_tags.end(); ++it )
			if (! merged_list.contains(*it))
				merged_list.append(*it);
		tlm->setStringList(merged_list);

	}
		
}

void MainWindowImpl::on_add_tag_clicked()
{
	QString new_tag = add_tag_entry->text();
	if (! new_tag.isEmpty() 
		&& ! photoview->isEmpty() 
		&& photoview->is_selection())
		handle_add_tag(new_tag);
}

void MainWindowImpl::handle_add_tag(const QString &new_tag)
{
	tag_list->add_tag(new_tag);
	tag_pool->add_tag(new_tag);
	photoview->add_tag_to_selected(new_tag);
	add_tag_entry->clear();
        saveAct->setEnabled(true);
}

void MainWindowImpl::on_photoview_selection_changed(const QItemSelection &,
const QItemSelection &)
{
	caption_entry->clear();
	tag_list->clear();
	caption_entry->setPlainText(photoview->get_selected_caption());
	QStringListModel *tlm = (QStringListModel *)tag_list->model();
	tlm->setStringList(photoview->get_selected_tag_list());
        // set all lens data to N/A
        max_aperture_sbox->setValue(0);
        fnumber_sbox->setValue(0);
        focal_sbox->setValue(0);
        //
        if (photoview->is_selection())
        {
            caption_entry->setEnabled(true);
            add_tag_button->setEnabled(true);
            add_tag_entry->setEnabled(true);
            add_button->setEnabled(true);
            remove_button->setEnabled(true);
            geotagAct->setEnabled(true);
            tag_list->setEnabled(true);
            tag_pool->setEnabled(true);
            lens_combo->setEnabled(true);
            max_aperture_sbox->setEnabled(true);
            fnumber_sbox->setEnabled(true);
            focal_sbox->setEnabled(true);
            lens_cbox->setEnabled(true);
            max_aperture_cbox->setEnabled(true);
            fnumber_cbox->setEnabled(true);
            focal_cbox->setEnabled(true);
            // set lens data
            QString model;
            Qt::CheckState model_checkbox;
            double max_aperture;
            Qt::CheckState max_aperture_checkbox;
            double fnum;
            Qt::CheckState fnum_checkbox;
            double focal;
            Qt::CheckState focal_checkbox;

            photoview->get_lens_data_for_selected(model,model_checkbox,
                                                  max_aperture,max_aperture_checkbox,
                                                  fnum,fnum_checkbox,
                                                  focal,focal_checkbox);
            if (! model.isEmpty() && lens_combo->findText(model) >= 0)
                lens_combo->setCurrentIndex(lens_combo->findText(model));
            else if (! model.isEmpty())
                lens_combo->insertItem(0, model);
            max_aperture_sbox->setValue(max_aperture);
            fnumber_sbox->setValue(fnum);
            focal_sbox->setValue(focal);
            lens_cbox->setCheckState(model_checkbox);
            max_aperture_cbox->setCheckState(max_aperture_checkbox);
            fnumber_cbox->setCheckState(fnum_checkbox);
            focal_cbox->setCheckState(focal_checkbox);
        }
        else
        {
            caption_entry->setEnabled(false);
            add_tag_button->setEnabled(false);
            add_tag_entry->setEnabled(false);
            add_button->setEnabled(false);
            remove_button->setEnabled(false);
            geotagAct->setEnabled(false);
            tag_list->setEnabled(false);
            tag_pool->setEnabled(false);
            lens_combo->setEnabled(false);
            max_aperture_sbox->setEnabled(false);
            fnumber_sbox->setEnabled(false);
            focal_sbox->setEnabled(false);
            lens_cbox->setEnabled(false);
            max_aperture_cbox->setEnabled(false);
            fnumber_cbox->setEnabled(false);
            focal_cbox->setEnabled(false);
        }

}

void MainWindowImpl::save()
{
    statusBar()->showMessage(tr("Saving the metadata..."));
    progressBar->show();
    QApplication::setOverrideCursor(Qt::WaitCursor);
    photoview->save_exif_data(progressBar);
    QApplication::restoreOverrideCursor();
    progressBar->hide();
    statusBar()->clearMessage();
    saveAct->setEnabled(false);
    QMessageBox::StandardButton reply;
    reply = QMessageBox::information(this, tr("IPTC Data Saved"),
                                     tr("Success! The IPTC info was updated in the photos."));
}

void MainWindowImpl::open()
{
        QSettings settings;
        QString dir = settings.value("lastUsedDir", QString("")).toString();
	QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Open Photos"), 
                                                 dir, tr("Image Files (*.jpg *.JPG)"));
	if (! fileNames.isEmpty())
	{
            QApplication::setOverrideCursor(Qt::WaitCursor);
            QStringList list = fileNames;
            QStringList::Iterator it = list.begin();
            settings.setValue("lastUsedDir", QFileInfo(*it).absolutePath());
            while( it != list.end() )
            {
			photoview->new_file( *it);
			statusBar()->showMessage(tr("Opening file: %1").arg(*it));
			++it;
            }
            QStringListModel *tpm = (QStringListModel *)tag_pool->model();
            tpm->setStringList(photoview->get_tag_list());
            QApplication::restoreOverrideCursor();
        }
	statusBar()->showMessage(tr("Ready"));
}

void MainWindowImpl::preferences()
{
    PreferencesDialog prefDlg(this);
    prefDlg.exec();
    // re-read the shortcuts
    shortcuts.clear();
    QSettings settings;
    int settings_size = settings.beginReadArray("shortcuts");
    for (int i = 0; i < settings_size; ++i) {
        settings.setArrayIndex(i);
        SHORTCUT shortcut;
        shortcut.key = settings.value("key").toInt();
        shortcut.modifiers = settings.value("modifiers").toUInt();
        shortcut.shortcut_text = settings.value("shortcut_text").toString();
        shortcut.keywords = settings.value("keywords").toString();
        shortcuts.append(shortcut);
    }
    settings.endArray();
}

void MainWindowImpl::on_tag_list_focus_in()
{
    tag_pool->clearSelection();
}

void MainWindowImpl::on_tag_pool_focus_in()
{
    tag_list->clearSelection();
}

void MainWindowImpl::on_photoview_delete_pressed()
{
    // refresh
    on_photoview_selection_changed(QItemSelection(), QItemSelection());
    if (photoview->isEmpty())
    {
        caption_entry->setEnabled(false);
        add_tag_button->setEnabled(false);
        add_tag_entry->setEnabled(false);
        add_button->setEnabled(false);
        remove_button->setEnabled(false);
        saveAct->setEnabled(false);
        geotagAct->setEnabled(false);
        tag_list->setEnabled(false);
        tag_pool->setEnabled(false);

    }
}

void MainWindowImpl::on_photoview_doubleclick(const QModelIndex &index)
{
    qDebug("pw doublecleck");
    photoview->display_picture_dialog(index);
}

void MainWindowImpl::about()
{
    QMessageBox::about(this, tr("About qPhotoTag"),
             tr("<center><h2>qPhotoTag %1</h2></center>"
        "qPhotoTag is inspired by <a href=\"http://www.itagsoftware.com\">iTag</a> that is why the UI "
        "is similar to the UI of iTag. The primary usecase for qPhotoTag is to add keywords, "
        "captions and GPS coordinates to digital camera photos in a way that is "
        "understood by Picasa.<br>"
        "<br>"
        "With qPhotoTag currently it is possible to add IPTC keywords and caption, add "
        "GPS coordinates from a waypoints.gpx file to both EXIF header and IPTC keywords. "
        "It has not been extensively tested, so make sure to back up your photos before "
        "running qPhotoTag on them.<br>"
        "<br>"
        "Copyright (c) 2009,2010 Marcell Lengyel <miketkf@gmail.com><br>"
        "<br>"
        "You may modify and redistribute the program under the terms of the GPL (version 2 or later).<br>"
        "We provide no warranty for this program."
        ).arg(QTAG_VERSION));
}

QString MainWindowImpl::select_waypoint_file()
{
    // select a .gpx file containing the waypoints
    return QFileDialog::getOpenFileName(this, tr("Open GPX file"),
                                        "", tr("GPX files (*.gpx *.GPX)"));
}

void MainWindowImpl::keyPressEvent(QKeyEvent *event)
{
    //qDebug("Key: %x modifyers: %lx %s\n", event->key(), ulong(event->nativeModifiers()), event->text().toAscii().data());
    if (photoview->hasFocus() && photoview->is_selection()) {
        //qDebug("Key: %x modifyers: %lx %s\n", event->key(), ulong(event->nativeModifiers()), event->text().toAscii().data());
        for (int i = 0; i < shortcuts.size(); ++i) {
            if ((shortcuts.at(i).key == event->key()) &&  (shortcuts.at(i).modifiers == event->nativeModifiers()))
                handle_add_tag(shortcuts.at(i).keywords);
        }
        //QMainWindow::keyPressEvent(event);
        event->accept();
    } else {
        QMainWindow::keyPressEvent(event);
        event->ignore();
    }

}
